import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class JspServlet implements Servlet {
    private String path = null;

    //通过set   动态改变当前请求的jsp
    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public void doGet(Request request, Response response) throws Exception {
        System.out.println("jspPath " + path);//  WebContent/test2.jsp

        String[] split = path.split("/");
        String s1 = split[split.length - 1];
        System.out.println("s1 "+s1);
        StringBuilder sb = new StringBuilder(s1);
        sb.replace(sb.indexOf("."), sb.indexOf(".") + 1, "_");
        sb.append(".java");//   test2_jsp.java
        String javaName = sb.toString();


        File file = new File("MyWebServer\\"+javaName);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        writer.write("public class "+javaName.split("\\.")[0]+"{\n");
        writer.write("  public String toJava(Response response," +
                "Request request)throws Exception{\n");
        //把含jsp标签的  内容转化


        File filex = new File(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filex)));
        String line = null;
        StringBuilder all = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            all.append(line+"\\n");
        }

        //排除头
        while (all.indexOf("<%@") != -1) {
            //public StringBuilder replace(int start,int end,String str)不包括end 故+2
            all.replace(all.indexOf("<%@"), all.indexOf("%>") + 2, "");
        }

        //扫描html标签里的“”
        int tag=0;
        for(int i=all.length()-1;i>0;i--)
        {
            if(all.charAt(i)=='>'&&all.charAt(i-1)=='%')
                tag=1;
            if(all.charAt(i)=='%'&&all.charAt(i-1)=='<')
                tag=0;
            if(tag==1)
                continue;
            if(all.charAt(i)=='\"')
            {
                all.replace(i,i+1,"\\\"");
            }
        }

        //扫描jsp标签<%=表达式%>
        while (all.toString().contains("<%=")) {
            String jspString = all.substring(all.indexOf("<%=") + 3, all.indexOf("%>",all.indexOf("<%=")));
            all.replace(all.indexOf("<%="), all.indexOf("%>",all.indexOf("<%=")) + 2, "\"+" + jspString + "+\"");
        }



        //写入html的所有内容
        String res = "    String str=\"" + all+ "\";";
        writer.write(res);


        writer.write("\n    return str;\n");

        writer.write("  }\n");
        writer.write("}\n");
        writer.close();



        String currentDir = System.getProperty("user.dir");
        // 使用JavaCompiler 编译java文件
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = jc.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(currentDir + "\\MyWebServer\\"+javaName);
        JavaCompiler.CompilationTask cTask = jc.getTask(null, fileManager, null, null, null, fileObjects);
        cTask.call();
        fileManager.close();

        URL[] urls = new URL[]{new URL("file:/" + currentDir + "/MyWebServer/")};
        URLClassLoader cLoader = new URLClassLoader(urls);
        Class<?> c = cLoader.loadClass(javaName.split("\\.")[0]);//test2_jsp
        cLoader.close();
        // 利用class创建实例，反射执行方法
        Object obj = c.newInstance();

        Method method = c.getMethod("toJava", Response.class, Request.class);
        String s = (String) method.invoke(obj, response, request);

        System.out.println("s :" + s);



        response.print(s);
    }

    @Override
    public void doPost(Request request, Response response) throws Exception {
        doGet(request, response);
    }
}
